import psutil
import tkinter as tk
from scapy.all import *
from tkinter import ttk, filedialog, messagebox
from tkinterdnd2 import DND_FILES, TkinterDnD
from uploadFile import FileUploader


# 获取当前主机的所有网卡名称
def get_adapters() -> list[str]:
    interfaces = psutil.net_if_addrs()
    interface_names = list(interfaces.keys())
    return interface_names


# 重放数据包
def replay_pcap():
    """
    读取指定数据包并将内容重放到指定网卡中

    :param filename: 数据包文件路径
    :param iface: 网卡名称
    :return: None
    """
    try:
        packets = rdpcap(file_path)  # 读取pcap文件中的数据包
        for packet in packets:
            sendp(packet, iface=get_selected_adapter(), verbose=0)  # 发送数据包到指定网卡
            print(f"Replaying packet: {packet.summary()}")  # 打印重放的数据包摘要
        messagebox.showinfo("Info", "Info: 数据包重放完毕")
    except Exception as e:
        messagebox.showerror("Error", f"Error: {e}")


def on_drop(event):
    global file_path
    file_path = event.data
    if file_path:
        file_path_label.config(text="已选择文件：" + file_path)
    else:
        file_path_label.config(text="未选择任何文件")


# 选择文件
def select_file():
    global file_path
    file_path = filedialog.askopenfilename()
    if file_path:
        file_path_label.config(text="已选择文件： " + file_path)
    else:
        file_path_label.config(text="未选择任何文件")


# 清空文件
def clear_file():
    file_path_label.config(text="未选择任何文件")


def get_selected_adapter():
    return selected_adapter.get()


if __name__ == '__main__':
    # 定义主窗口的大小
    window_width = 600
    window_height = 400

    # 创建主窗口
    root = TkinterDnD.Tk()

    # 获取当前屏幕的宽度和高度
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()

    # 将主窗口定位到屏幕中心
    x = (screen_width // 2) - (window_width // 2)
    y = (screen_height // 2) - (window_height // 2)
    root.geometry(f"{window_width}x{window_height}+{x}+{y}")

    # 设置标题
    root.title("数据包重放器")

    """ 网卡选择框 """
    # 创建选择网卡文本标签
    select_adapter_label = ttk.Label(root, text="选择网卡：")
    select_adapter_label.grid(padx=(30, 0), pady=(10, 5))

    # 创建一个变量来存储选择的网卡
    selected_adapter = tk.StringVar()

    # 定义选项列表
    adapters = get_adapters()

    # 创建选择网卡的下拉框
    select_adapter_box = ttk.Combobox(root, textvariable=selected_adapter, values=adapters, width=50)
    select_adapter_box.grid(row=0, column=1, padx=0, pady=(10, 5))

    # 设置下拉菜单默认的选项
    select_adapter_box.current(0)

    """ 上传数据包文件 """
    # 声明文件路径
    file_path = ""
    # 创建文件上传区域
    upload_file_area = tk.LabelFrame(root, text="文件上传区域")
    upload_file_area.grid(row=1, column=0, columnspan=2, padx=30, pady=(10, 10), sticky=tk.W+tk.E)
    upload_file_area.drop_target_register(DND_FILES)
    upload_file_area.dnd_bind('<<Drop>>', on_drop)

    # 创建显示文件路径的标签
    file_path_label = tk.Label(upload_file_area, text="未选择任何文件", wraplength=400)
    file_path_label.grid(row=0, column=0, columnspan=2, padx=20, pady=10)

    # 创建选择文件按钮
    select_file_button = tk.Button(upload_file_area, text="选择文件", command=select_file)
    select_file_button.grid(row=1, column=0, padx=10, pady=10)

    # 创建清空文件按钮
    clear_file_button = tk.Button(upload_file_area, text="清空文件", command=clear_file)
    clear_file_button.grid(row=1, column=1, padx=10, pady=10)


    """ 数据包重放按钮 """
    interface = get_selected_adapter()
    begin_button = tk.Button(root, text="开始", command=replay_pcap, width=10)
    begin_button.grid(row=2, column=1)




    root.mainloop()
